/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.admin;

import dao.DanhmucDAO;
import dao.LoaispDAO;
import dao.NguoidungDAO;
import dao.SanphamDAO;
import dao.TinhtrangDAO;
import java.io.*;
import java.util.ArrayList;
import java.sql.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import pojo.Danhmuc;
import pojo.Loaisp;
import pojo.Nguoidung;
import pojo.Sanpham;
import pojo.Tinhtrang;

/**
 *
 * @author kydrenw
 */
public class SanPhamController implements Controller {

    @Override
    public ModelAndView handleRequest(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {

        hsr1.setCharacterEncoding("UTF-8");
        
        Nguoidung nguoiDung =(Nguoidung) hsr.getSession().getAttribute("nguoiDung");
        if (nguoiDung==null || !NguoidungDAO.laQuanLy(nguoiDung.getTendangnhap()) ) {           
            hsr.setAttribute("tag", "no");
            return new ModelAndView("admin/index");
        }

        if (hsr.getParameter("image") != null) {
            hsr.setAttribute("image", hsr.getParameter("image"));
        }

        if (hsr.getParameter("action") != null) {
            String action = hsr.getParameter("action").toString();

            if (action.equals("them")) {
                return themSanPham(hsr, hsr1);
            }

            if (action.equals("sanpham_them_submit")) {
                return themSanPham_Submit(hsr, hsr1);
            }

            if (action.equals("sua")) {
                return suaSanPham(hsr, hsr1);
            }

            if (action.equals("sua_submit")) {
                return suaSanPham_Submit(hsr, hsr1);
            }

            if (action.equals("xoa")) {
                return xoaSanPham(hsr, hsr1);
            }

            if (action.equals("upload")) {
                return upload(hsr, hsr1);
            }

            if (action.equals("timkiem")) {
                return timSanPham(hsr, hsr1);
            }

            if (action.equals("mapping")) {
                mapping(hsr, hsr1);
            }
        }

        return hienDanhSachSanPham(hsr, hsr1);
    }

    private ModelAndView hienDanhSachSanPham(HttpServletRequest hsr, HttpServletResponse hsr1) {
        hsr.setAttribute("tag", "sanpham_danhsach");
        List<Sanpham> all = SanphamDAO.layDanhSach();

        int rows = 5;
        int totalPages = (int) Math.floor((all.size() - 1) / (float) rows) + 1;
        int pageNumber = 1;
        int fromIndex = 0;
        int toIndex = 0;

        if (hsr.getParameter("page") != null) {
            pageNumber = Integer.parseInt(hsr.getParameter("page"));
            if (pageNumber == totalPages) {
                fromIndex = (pageNumber - 1) * rows;
                toIndex = fromIndex + all.size()
                        - (rows * (totalPages - 1));
            } else {
                fromIndex = (pageNumber - 1) * rows;
                toIndex = fromIndex + rows;
            }
            List<Sanpham> ds = all.subList(fromIndex, toIndex);
            hsr.setAttribute("ds", ds);
        } else {
            List<Sanpham> ds = all.subList(0, rows);
            hsr.setAttribute("ds", ds);
        }

        hsr.setAttribute("page", pageNumber);
        hsr.setAttribute("totalPages", totalPages);

        return new ModelAndView("admin/index");
    }

    private ModelAndView themSanPham(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {
        hsr.setAttribute("tag", "sanpham_them");

        List<Danhmuc> dsDanhMuc = DanhmucDAO.layDanhSach();
        hsr.setAttribute("dsDanhMuc", dsDanhMuc);
        Danhmuc dmSel;

        if (hsr.getParameter("txtDanhMuc") != null) {
            int madmSel = Integer.parseInt(hsr.getParameter("txtDanhMuc").toString());
            dmSel = DanhmucDAO.layThongTin(madmSel);
        } else {
            dmSel = dsDanhMuc.get(0);
        }

        hsr.setAttribute("dmSel", dmSel);

        Object[] dsTemp = dmSel.getLoaisps().toArray();
        ArrayList< Loaisp> dsLoai = new ArrayList<Loaisp>();
        for (int i = 0; i < dsTemp.length; i++) {
            dsLoai.add((Loaisp) dsTemp[i]);
        }

        hsr.setAttribute("dsLoaiSP", dsLoai);
        return new ModelAndView("admin/index");
    }

    private ModelAndView suaSanPham(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {
        hsr.setAttribute("tag", "sanpham_sua");

        Integer ma = Integer.parseInt(hsr.getParameter("ma"));
        Sanpham sp = SanphamDAO.layThongTin(ma);
        hsr.setAttribute("sanpham", sp);

        List<Danhmuc> dsDanhMuc = DanhmucDAO.layDanhSach();
        hsr.setAttribute("dsDanhMuc", dsDanhMuc);

        Danhmuc dm = sp.getLoaisp().getDanhmuc();
        hsr.setAttribute("danhmucSel", dm);
        hsr.setAttribute("dsLoai", dm.getLoaisps());
        hsr.setAttribute("loaiSel", sp.getLoaisp());
        //1 : loai tinh trang san pham
        List<Tinhtrang> dsTinhTrang = TinhtrangDAO.layDanhSach(1);
        hsr.setAttribute("dsTinhTrang", dsTinhTrang);

        return new ModelAndView("admin/index");
    }

    private ModelAndView upload(HttpServletRequest hsr, HttpServletResponse hsr1) throws ServletException, IOException {
        hsr.setAttribute("tag", "sanpham_them");

        List<Danhmuc> dsDanhMuc = DanhmucDAO.layDanhSach();
        hsr.setAttribute("dsDanhMuc", dsDanhMuc);

        List<Loaisp> dsLoaiSP = LoaispDAO.layDanhSach();
        hsr.setAttribute("dsLoaiSP", dsLoaiSP);

        //to get the content type information from JSP Request Header
        String contentType = hsr.getContentType();
        //here we are checking the content type is not equal to Null and  as well as the passed data from mulitpart
        //form - data is greater than or equal to 0
        if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
            DataInputStream in = new DataInputStream(hsr.getInputStream());
            //we are taking the length of Content type data
            int formDataLength = hsr.getContentLength();
            byte dataBytes[] = new byte[formDataLength];
            int byteRead = 0;
            int totalBytesRead = 0;
            //this loop converting the uploaded file into byte code
            while (totalBytesRead < formDataLength) {
                byteRead = in.read(dataBytes, totalBytesRead,
                        formDataLength);
                totalBytesRead += byteRead;
            }
            String file = new String(dataBytes);
            //for saving the file name
            String saveFile = file.substring(file.indexOf("filename=\"") + 10);
            saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
            saveFile = saveFile.substring(saveFile.lastIndexOf("\\")
                    + 1, saveFile.indexOf("\""));
            int lastIndex = contentType.lastIndexOf("=");
            String boundary = contentType.substring(lastIndex + 1,
                    contentType.length());
            int pos;
            //extracting the index of file
            pos = file.indexOf("filename=\"");
            pos = file.indexOf("\n", pos) + 1;
            pos = file.indexOf("\n", pos) + 1;
            pos = file.indexOf("\n", pos) + 1;
            int boundaryLocation = file.indexOf(boundary, pos) - 4;
            int startPos = ((file.substring(0, pos)).getBytes()).length;
            int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
            // creating a new file with the same name and writing the
            // content in new file
            FileOutputStream fileOut = new FileOutputStream(saveFile);
            fileOut.write(dataBytes, startPos, (endPos - startPos));
            fileOut.flush();
            fileOut.close();
        }

        return new ModelAndView("admin/index");
    }

    private ModelAndView xoaSanPham(HttpServletRequest hsr, HttpServletResponse hsr1) {
        int ma = Integer.parseInt(hsr.getParameter("ma"));
        SanphamDAO.xoaSanPham(ma);

        return hienDanhSachSanPham(hsr, hsr1);
    }

    private ModelAndView timSanPham(HttpServletRequest hsr, HttpServletResponse hsr1) {
        hsr.setAttribute("tag", "sanpham_danhsach");
        String tukhoa = hsr.getParameter("txttukhoa");
        int danhmuc = Integer.parseInt(hsr.getParameter("danhmuc"));
        List<Sanpham> all = SanphamDAO.timKiem(tukhoa, danhmuc);

        int rows = 5;
        int totalPages = (int) Math.floor((all.size() - 1) / (float) rows) + 1;
        int pageNumber = 1;
        int fromIndex = 0;
        int toIndex = 0;

        if (hsr.getParameter("page") != null) {
            pageNumber = Integer.parseInt(hsr.getParameter("page"));
            if (pageNumber == totalPages) {
                fromIndex = (pageNumber - 1) * rows;
                toIndex = fromIndex + all.size()
                        - (rows * (totalPages - 1));
            } else {
                fromIndex = (pageNumber - 1) * rows;
                toIndex = fromIndex + rows;
            }
            List<Sanpham> ds = all.subList(fromIndex, toIndex);
            hsr.setAttribute("ds", ds);
        } else {
            hsr.setAttribute("ds", all);
        }

        hsr.setAttribute("page", pageNumber);
        hsr.setAttribute("totalPages", totalPages);

        return new ModelAndView("admin/index");
    }

    private ModelAndView themSanPham_Submit(HttpServletRequest hsr, HttpServletResponse hsr1) throws UnsupportedEncodingException {
        hsr.setAttribute("tag", "sanpham_them");
        hsr.setCharacterEncoding("UTF-8");
        hsr1.setCharacterEncoding("UTF-8");
        List<Danhmuc> dsDanhMuc = DanhmucDAO.layDanhSach();
        hsr.setAttribute("dsDanhMuc", dsDanhMuc);

        List<Loaisp> dsLoaiSP = LoaispDAO.layDanhSach();
        hsr.setAttribute("dsLoaiSP", dsLoaiSP);

        Sanpham sp = new Sanpham();

        if (hsr.getParameter("txtLoai") != null) {
            int maLoai = Integer.parseInt(hsr.getParameter("txtLoai"));
            sp.setLoaisp(LoaispDAO.layThongTin(maLoai));
        }
        if (hsr.getParameter("txtGia") != null) {
            float gia = Float.parseFloat(hsr.getParameter("txtGia"));
            sp.setGia(gia);
        }
        if (hsr.getParameter("txtSoLuong") != null) {
            int soluong = Integer.parseInt(hsr.getParameter("txtSoLuong"));
            sp.setSoluongton(soluong);
        }
        if (hsr.getParameter("txtTenSP") != null) {
            sp.setTensp(hsr.getParameter("txtTenSP"));
        }
        if (hsr.getParameter("txtMieuTa") != null) {
            sp.setMota(hsr.getParameter("txtMieuTa"));
        }
        Date time = new Date(System.currentTimeMillis());
        sp.setNgaydang(time);

        String hinhAnh = "product/" + hsr.getParameter("image");
        sp.setHinhanh(hinhAnh);

        if (SanphamDAO.themSanPham(sp) == true) {
            hsr.setAttribute("message", "Thêm thành công !");
        } else {
            hsr.setAttribute("message", "Thao tác thất bại . Xin thử lại !");
        }
        return new ModelAndView("admin/index");
    }

    private ModelAndView suaSanPham_Submit(HttpServletRequest hsr, HttpServletResponse hsr1) {
        hsr.setAttribute("tag", "sanpham_sua");
        int masp = Integer.parseInt(hsr.getParameter("masp").toString());
        Sanpham sp = SanphamDAO.layThongTin(masp);
        String tenSP = hsr.getParameter("txttensp");
        float giaSP = Float.parseFloat(hsr.getParameter("txtgia").toString());
        int soluong = Integer.parseInt(hsr.getParameter("txtsoluong").toString());
        int madanhmuc = Integer.parseInt(hsr.getParameter("txtdanhmuc").toString());
        int maloai = Integer.parseInt(hsr.getParameter("txtloaisp").toString());
        
        int matinhtrang = Integer.parseInt(hsr.getParameter("tinhtrang").toString());
        String mieuta = hsr.getParameter("txtmieuta");
        String hinhanh = hsr.getParameter("txtImage");
        sp.setTensp(tenSP);
        sp.setGia(giaSP);
        sp.setSoluongton(soluong);
        Loaisp loai = LoaispDAO.layThongTin(maloai);
        hsr.setAttribute("loaiSel", loai);
        sp.setLoaisp(loai);
        sp.setTinhtrang(new Tinhtrang(matinhtrang));
        sp.setMota(mieuta);
        sp.setHinhanh(hinhanh);
        SanphamDAO.suaSanPham(sp);

        hsr.setAttribute("sanpham", sp);

        List<Danhmuc> dsDanhMuc = DanhmucDAO.layDanhSach();
        hsr.setAttribute("dsDanhMuc", dsDanhMuc);
        Danhmuc dm = DanhmucDAO.layThongTin(madanhmuc);
        hsr.setAttribute("danhmucSel", dm);
        hsr.setAttribute("dsLoai", dm.getLoaisps());

        //1 : loai tinh trang san pham
        List<Tinhtrang> dsTinhTrang = TinhtrangDAO.layDanhSach(1);
        hsr.setAttribute("dsTinhTrang", dsTinhTrang);

        hsr.setAttribute("message", "Cập nhật thành công !");
        return new ModelAndView("admin/index");
    }

    private void mapping(HttpServletRequest request, HttpServletResponse hsr1) {
        HttpSession session = request.getSession();
        session.setAttribute("txtDanhMuc", request.getParameter("d"));
        session.setAttribute("txtLoai", request.getParameter("l"));
        session.setAttribute("txtTenSP", request.getParameter("t"));
        session.setAttribute("txtGia", request.getParameter("g"));
        session.setAttribute("txtSoLuong", request.getParameter("s"));
        session.setAttribute("txtMieuTa", request.getParameter("m"));       
    }
}